import random

from django.http import HttpResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_mall.libs.yuntongxun.sms import CCP
from meiduo_mall.utils.captcha.captcha import captcha
from verifications import constans
import logging

logger = logging.getLogger('django')


# 获取图片验证码
# GET /image_codes/(?P<image_code_id>\d+)/
class GetImageCode(APIView):
    def get(self,request,image_code_id):

        # 调用generate_captcha获取图片验证码编号,验证码值,图片(二进制)
        name, text, image_data = captcha.generate_captcha()

        redis_conn = get_redis_connection('default')

        # 将图片验证码的值保存redis
        try:
            # 参数1: key,  参数2: value,  参数3: 有效期
            redis_conn.set("image_code:%s" % image_code_id, text, 300)

        except Exception as e:
            logger.info(e)
            return "图片验证码操作失败"

        # 4.返回图片
        response = HttpResponse(content=image_data,content_type='image/png')

        return response



# 专门获取短信的一个子应用
# GET  /sms_codes/(?P<mobile>1[3-9]\d{9})/?text=填写的验证码&image_code_id=asdasdas2123
# 参数:mobile,text,image_code_id
# 返回值{'message':'OK'}
class SmsCodeView(APIView):
    # get请求方法
    def get(self,request,mobile):
        image_code = request.query_params.get('text')
        image_code_id = request.query_params.get('image_code_id')
        redis_conn = get_redis_connection('default')
        # 取出真实的图片验证码
        image_code_real = redis_conn.get("image_code:%s" % image_code_id)
        if not image_code_real:
            return Response({'message':'图片验证码过期'})
        # 判断图片验证码是否正确
        image_code_real=image_code_real.decode()
        if image_code.upper() != image_code_real.upper():
            return Response({'message':'图片验证码错误'})

        # 删除redis中的图片验证码
        redis_conn.delete("image_code:%s" % image_code_id)

        # 获取专属verify短信码2号数据库的redis对象
        redis_conn = get_redis_connection('verify_codes')

        # 判断验证码是否存在redis中
        if redis_conn.get('sms_code_flag_%s'%mobile):
            return Response({'message':'发送验证码过于频繁'},status=status.HTTP_403_FORBIDDEN)

        # 1 生成验证码
        sms_code = "%06d" % random.randint(0,999999)
        print(sms_code)
        # 记录到日志文件中,只是方便查看
        logger.info('短信验证码：%s'% sms_code)

        # 2 创建管道对象 发送短信
        pl = redis_conn.pipeline()
        # 将短信验证码存入redis3号库
        pl.setex('sms_code_%s' % mobile, constans.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 存一个flag记录用户频次60s/次,防止用户狂点发送短信,浪费钱
        pl.setex('sms_code_flag_%s' % mobile, constans.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        # redis_conn.setex('sms_code_%s'%mobile, constans.SMS_CODE_REDIS_EXPIRES,sms_code)
        # # 防止用户狂点发送短信,浪费钱
        # redis_conn.setex('sms_code_flag_%s'%mobile,constans.SEND_SMS_CODE_INTERVAL,1)

        #　用云通信发送
        expires = constans.SMS_CODE_REDIS_EXPIRES//60

        # 使用celery扩展 创建第三方独立进程进行发短信操作,这边直接给客户端返回响应
        # from celery_tasks.sms.tasks import send_sms_code
        # send_sms_code.delay(mobile,sms_code,expires)


        '''try:
             # 注意： 测试的短信模板编号为1
             # 参数1: 要给哪个手机号发送短信    参数2: ["验证码",有效期]  参数3: 模板编号默认就是1
             ret = ccp.send_template_sms(mobile, [sms_code, expires], constans.SEND_SMS_TEMP_ID)
         except Exception as e:
             logger.error(e)
             return Response({'message':'短信发送异常'},status=status.HTTP_503_SERVICE_UNAVAILABLE)
         if ret == -1:
             return Response({'message':'发送短信失败'})
        '''

        # 返回响应 状态码默认是200
        return Response({'message':'OK'})
